package com.zywl.web.controller.sys;

import com.zywl.core.beans.Resource;
import com.zywl.core.beans.Role;
import com.zywl.core.beans.User;
import com.zywl.service.DictionaryService;
import com.zywl.service.ResourceService;
import com.zywl.service.RoleService;
import com.zywl.service.UserService;
import com.zywl.utils.models.AjaxResult;
import com.zywl.utils.models.PageData;
import com.zywl.utils.models.PageResult;
import com.zywl.utils.utils.Constants;
import com.zywl.utils.utils.GenerateCodeUtil;
import com.zywl.utils.utils.MapUtil;
import com.zywl.utils.utils.enums.LogTypeEnum;
import com.zywl.web.controller.base.BaseController;
import com.zywl.web.controller.form.RoleForm;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@RestController
@RequestMapping("/role")
public class RoleController extends BaseController {
    @Autowired
    private DictionaryService dictionaryService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private ResourceService resourceService;
    @Autowired
    private UserService userService;

    @GetMapping("/roleListPage")
    public ModelAndView roleListPage() {
        ModelAndView mav = new ModelAndView("role/roleListPage");
        return mav;
    }

    @PostMapping("/getRoleList")
    public PageResult getRoleList(HttpServletRequest request, PageData pageData) {
        Map<String, Object> condition = MapUtil.changeMap(request.getParameterMap());
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION_KEY);
        PageResult pageResult = null;
        try {
            if(user.getUsrAssociationId() != null){
                condition.put("roeAssociationId",user.getUsrAssociationId());
            }
            pageResult = putToResult(roleService.getPageInfo(condition, pageData));
        } catch (Exception e) {
            logger.error("获取角色列表异常", e);
        }
        return pageResult;
    }

    @GetMapping("/roleSubmitPage")
    public ModelAndView roleSubmitPage(String id, HttpSession session) {
        ModelAndView mav = new ModelAndView("role/roleSubmitPage");
        try {
            if (StringUtils.isNotEmpty(id)) {
                Role role = roleService.getById(Long.parseLong(id));
                mav.addObject("role", role);

                if (role != null) {
                    List<Resource> resources = resourceService.getResourcesByRoleId(role.getRoeId(), null);
                    StringBuilder sb = new StringBuilder();
                    for (Resource resource : resources) {
                        sb.append(Constants.STRING_SPLIT);
                        sb.append(resource.getResId());
                    }
                    if (resources != null && !resources.isEmpty()) {
                        sb.append(Constants.STRING_SPLIT);
                        sb.append(Constants.RESOURCE_ROOT_PARENT);
                    }
                    if (sb.length() > 0) {
                        mav.addObject("ids", sb.deleteCharAt(0).toString());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取数据异常", e);
        }
        return mav;
    }

    @PostMapping("/roleSubmit")
    public AjaxResult roleSubmit(HttpServletRequest request, RoleForm form) {
        AjaxResult ar = new AjaxResult();
        Date date = new Date();
        if (form != null) {
            Long id = form.getRoeId();
            Role role = null;
            String old = null;
            try {
                if (id == null) {
                    role = new Role();
                } else {
                    role = roleService.getById(id);
                    form.setRoeStt(role.getRoeStt());
                    form.setRoeCreateTime(role.getRoeCreateTime());
                    old = role.getRoeName();
                }
                BeanUtils.copyProperties(form, role);
                role.setRoeModifyTime(date);

                if (id == null) {
                    role.setRoeStt("0");
                    role.setRoeCreateTime(date);

                    roleService.save(role, form.getIds());
                } else {
                    roleService.update(role, form.getIds());
                }
            } catch (Exception e) {
                logger.error("提交角色信息异常", e);
                ar.error("提交角色信息异常", e);
                return ar;
            }

            if (id == null) {
                saveLog(request, LogTypeEnum.ROLE.getKey(), "角色新增-" + form.getRoeName());
                ar.success("新增成功");
            } else if (old != null && !old.equals(form.getRoeName())) {
                saveLog(request, LogTypeEnum.ROLE.getKey(), "角色修改-" + old + "→" + form.getRoeName());
                ar.success("修改成功");
            } else {
                saveLog(request, LogTypeEnum.ROLE.getKey(), "角色修改-" + form.getRoeName());
                ar.success("修改成功");
            }
        } else {
            ar.error("提交失败，参数为空");
        }
        return ar;
    }

    @PostMapping("/roleDelete")
    public AjaxResult roleDelete(HttpServletRequest request, String id) {
        AjaxResult ar = new AjaxResult();
        try {
            if("1".equals(id)){
                ar.error("该角色为超级系统管理员无法删除。");
                return ar;
            }
            Role role = roleService.getById(Long.parseLong(id));
            String roleName = Constants.STRING_NULL;

            boolean flag = true;
            if (role != null) {
                roleName = role.getRoeName();
                List<User> users = userService.getUsersByRoleId(role.getRoeId().toString());
                if (users != null && !users.isEmpty()) {
                    flag = false;
                }
            }

            if (flag) {
                roleService.deleteById(Long.parseLong(id));

                saveLog(request, LogTypeEnum.ROLE.getKey(), "角色删除-" + roleName);
                ar.success("删除成功");
            } else {
                ar.error("删除失败，该角色已被使用");
            }
        } catch (Exception e) {
            ar.error("删除角色异常", e);
            logger.error("删除角色异常", e);
        }
        return ar;
    }
}
